﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Gurucore.Framework.Core;
using Gurucore.Framework.Core.Activation;
using Gurucore.Framework.Core.Factory;
using Gurucore.Framework.Core.Util;
using Gurucore.Framework.Business.TransactionContext;

namespace Gurucore.Framework.Business
{
	public class ServiceFactory : FactoryBase<ServiceInfo>
	{
		public ServiceFactory(string p_sDescriptorFile)
			: base(p_sDescriptorFile)
		{
		}

		public object GetImplementation(Type p_oInterface, object[] p_arrParam)
		{
			string sInterfaceName = p_oInterface.FullName;

			ServiceInfo oServiceInfo = this.GetItem(sInterfaceName);
			object oService = null;
			if ((oServiceInfo != null) && (!oServiceInfo.ImplementationClass.NullOrEmpty()))
			{
				DynamicActivator oDynActivator = Application.GetInstance().GetGlobalSharedObject<DynamicActivator>();
				object[] arrFullParam = new object[oServiceInfo.ActivationParam.Count + p_arrParam.Length];
				for (int i = 0; i < oServiceInfo.ActivationParam.Count; i++)
				{
					arrFullParam[i] = oServiceInfo.ActivationParam[i];
				}
				p_arrParam.CopyTo(arrFullParam, oServiceInfo.ActivationParam.Count);
				oService = oDynActivator.GetObject(oServiceInfo.ImplementationAssembly, oServiceInfo.ImplementationClass, arrFullParam);
			}
			else
			{
				//by naming convention Company.Package.IServiceName -> Company.Package.ServiceName, activate the proxy
				string sDefaultImplementation = p_oInterface.Namespace + "." + p_oInterface.Name.Substring(1);
				Type oServiceType = p_oInterface.Assembly.GetType(sDefaultImplementation);
				TransactionalServiceProxier oProxier = new TransactionalServiceProxier();
				Type oServiceProxyType = oProxier.GetProxyClass(oServiceType);
				oService = Activator.CreateInstance(oServiceProxyType, p_arrParam);
			}
			return oService;
		}
	}
}
